const generate = require('nanoid/generate')
Parse.Cloud.beforeSave('RcCircle', async (req, res) => {
  try {
    const circle = req.object
    if (!circle.id) {
      const code = generate('0123456789', 5)
      circle.set('code', code)
      circle.set('lastUpdateTime',new Date())

      const member = circle.get('member')
      member.increment('circleTotal', 1).save()
    } else {
      const currentStatus = circle.get('status')
      if (currentStatus === -1) {
        const pre = await new Parse.Query('RcCircle').equalTo('objectId', circle.id).first()
        const preStatus = pre.get('status')
        if (preStatus !== currentStatus) {
          const member = circle.get('member')
          member.increment('circleTotal', -1).save()
        }
      }
    }
    res.success(circle)
  } catch (err) {
    res.error(err.message)
  }
})
